package io.bhex.app.market.presenter;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.base.AppUI;
import io.bhex.app.market.adapter.MarketListMultiAdapter;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-01-09
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class MarketRankingPresenter extends BaseFragmentPresenter<MarketRankingPresenter.MarketRankingUI> {
    private static final int RETRY_SUB = 0;
    private int marketType = AppData.TICKER.MARKET_TYPE_ALL;
    private HashMap<String, CoinPairBean> currentMarketMap;
    private Handler handler;

    public interface MarketRankingUI extends AppUI{

        void showMarketList(List<CoinPairBean> marketList);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, MarketRankingUI ui) {
        super.onUIReady(activity, ui);


        Bundle arguments = getFragment().getArguments();
        if (arguments != null) {
            marketType = arguments.getInt(AppData.INTENT.MARKET_TYPE, AppData.TICKER.MARKET_TYPE_BB);
            setMarketMap(marketType);
        }

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (TextUtils.isEmpty(SymbolDataManager.GetInstance().getOrgId())) {
                    handler.sendEmptyMessageDelayed(RETRY_SUB, 30);
                }else{
                    subReqTopN(marketType);
                }
            }
        };

    }

    private void setMarketMap(int marketType) {
        switch (marketType){
            case AppData.TICKER.MARKET_TYPE_BB:
                currentMarketMap = SymbolDataManager.GetInstance().getBBSymbolMap();
                break;
            case AppData.TICKER.MARKET_TYPE_CONTRACT:
                currentMarketMap = SymbolDataManager.GetInstance().getContractSymbolMap();
                break;
            case AppData.TICKER.MARKET_TYPE_OPTION:
                currentMarketMap = SymbolDataManager.GetInstance().getOptionSymbolMap();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        DebugLog.e("RANK-MARKET-onResume",this.hashCode() + "  onResume ");
    }

    @Override
    public void onPause() {
        super.onPause();
        DebugLog.e("RANK-MARKET-onPause",this.hashCode() + "  onPause ");
    }

    @Override
    public void setUserVisibleHint(boolean userVisibleHint) {
        super.setUserVisibleHint(userVisibleHint);
        DebugLog.e("RANK-MARKET-setUserVisibleHint",this.hashCode() + " " + userVisibleHint);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        DebugLog.e("RANK-MARKET-onHiddenChanged",this.hashCode() + " " + hidden);
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        DebugLog.e("RANK-MARKET-onVisibleChanged",this.hashCode() + " " + visible);
        if (visible) {
            setMarketMap(marketType);
//            if (currentMarketMap == null) {
//                //如果默认没有拿到SymbolMap，主动再获取一次
//                setMarketMap(marketType);
//            }
            //订阅当前行情
            if (TextUtils.isEmpty(SymbolDataManager.GetInstance().getOrgId())) {
                handler.sendEmptyMessageDelayed(RETRY_SUB,0);
            }else{
                subReqTopN(marketType);
            }

        }else{
            unSubReqTopN(marketType);
        }
    }

    private void subReqTopN(int marketType) {
        QuoteApi.SubTopN(marketType, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI().isAlive() || response == null)
                    return;
                List<CoinPairBean> marketList = handleTickersToMarketList(response.getData());
                getUI().showMarketList(marketList);

            }

            @Override
            public void onError(String response) {

            }
        });
    }

    private List<CoinPairBean> marketList = new ArrayList<>();

    /**
     * 将tickers 转换成 market list
     * @param tickerBeanList
     * @return
     */
    private List<CoinPairBean> handleTickersToMarketList(List<TickerBean> tickerBeanList) {
        marketList.clear();
        if (currentMarketMap == null || currentMarketMap.size()<1) {
            //未拿到币对信息
            DebugLog.e("error info : 未拿到币对信息");
            setMarketMap(marketType);
            return marketList;
        }
        if (tickerBeanList != null) {
            for (TickerBean data : tickerBeanList) {
                CoinPairBean coinPairBean = currentMarketMap.get(data.getS());
                if (coinPairBean != null) {
                    switch (marketType){
                        case AppData.TICKER.MARKET_TYPE_BB:
                            coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_BB);
                            break;
                        case AppData.TICKER.MARKET_TYPE_CONTRACT:
                            coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_FUTURES);
                            break;
                        case AppData.TICKER.MARKET_TYPE_OPTION:
                            coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_OPTION);
                            break;
                    }
                    coinPairBean.setTicker(data);
                    marketList.add(coinPairBean);
                }
            }
        }
        return marketList;
    }

    /**
     * 取消订阅
     * @param marketType
     */
    private void unSubReqTopN(int marketType) {
        QuoteApi.UnSubTopN("topN"+marketType);
    }

}
